<?php

namespace App\Store\Controllers\Financial\Business;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
/**
 * 毛利
 */
class GrossProfitsController extends Controller
{

    public function getlist(Request $request){

        $store_id=intval($request->store_id);
        if($store_id<=0){
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }
        $where=[];
        $where[]=['store_id',$store_id];
        $where[]=['audit_status',2];
        $where[]=['is_del',1];

        $goods_category_id = intval($request->goods_category_id);
        if ($goods_category_id>0 ) {
            $where[]=['goods_category_id',$goods_category_id];
        }

        $order_at_start=strtotime($request->order_at_start);
        $order_at_end=strtotime($request->order_at_end);
        if($order_at_start>0 && $order_at_end>$order_at_start){
            $where[]=['order_at','>=',$order_at_start];
            $where[]=['order_at','<=',$order_at_end];
        }

        $is_sujin = intval($request->is_sujin);
        if ($is_sujin>0 ) {
            $where[]=['is_sujin',$is_sujin];
        }

        $where1=[];
        $where1[]=['red_status',1];

        $goods_cabinetgroup_id = intval($request->goods_cabinetgroup_id);
        if ($goods_cabinetgroup_id>0 ) {
            $where1[]=['goods_cabinetgroup_id',$goods_cabinetgroup_id];
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        if ($accountinfo['type'] == 11) {
            $sales_where = $where1 + [
                ['total_money', '>', $training['training_min']],
                ['total_money', '<', $training['training_max']],
            ];
        } else {
            $sales_where = $where1;
        }
        $list1=OrderSalesGoods::where($where)->where($sales_where)->select(['goods_category_id'])->groupBy('goods_category_id');

        if ($accountinfo['type'] == 11) {
            $sales_recovery_where = $where + [
                ['money', '>', $training['training_min']],
                ['money', '<', $training['training_max']],
            ];
        } else {
            $sales_recovery_where = $where;
        }
        $list2=OrderSalesRecoveryGoods::where($sales_recovery_where)->select(['goods_category_id'])->groupBy('goods_category_id');

        if ($accountinfo['type'] == 11) {
            $recovery_where = $where + [
                ['money', '>', $training['training_min']],
                ['money', '<', $training['training_max']],
            ];
        } else {
            $recovery_where = $where;
        }
        $list3=OrderRecoveryGoods::where($recovery_where)->select(['goods_category_id'])->groupBy('goods_category_id');
        $list=$list1->union($list2)->union($list3)->get()->toArray();



        $list_new=[];

        $store_name=SiteStore::where(['id'=>$store_id])->value('store_name');
        foreach($list as $val){
            $val['store_name']=$store_name;
            $item=[];
            $item['store_name']=$store_name;
            $item['goods_category_name']=GoodsCategory::where(['id'=>$val['goods_category_id']])->value('category_name');
            $item['count']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('count');
            $item['weight']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->where(['is_gram'=>2])->sum('weight');
            $item['netglod_weight']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->where(['is_gram'=>1])->sum('weight');
            $item['total_money']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('total_money');
            $item['cost_fee']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('cost_fee');
            $item['recovery_money']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('money');

            $item['recovery_count']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('count')+OrderRecoveryGoods::where($where)->where([['goods_category_id',$val['goods_category_id']]])->sum('count');
            $item['recovery_weight']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where([['goods_category_id',$val['goods_category_id']]])->sum(DB::raw('weight*count'))+OrderRecoveryGoods::where($where)->where([['goods_category_id',$val['goods_category_id']]])->sum(DB::raw('weight*count'));
            $item['recovery_dold_fee']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('dold_fee')+OrderRecoveryGoods::where($where)->where([['goods_category_id',$val['goods_category_id']]])->sum('dold_fee');
            $item['recovery_valuations']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('valuations')+OrderRecoveryGoods::where($where)->where([['goods_category_id',$val['goods_category_id']]])->sum('valuations');

            $item['recovery_count_change_type2']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where('change_type',2)->where([['goods_category_id',$val['goods_category_id']]])->sum('count')+OrderRecoveryGoods::where($where)->where('change_type',2)->where([['goods_category_id',$val['goods_category_id']]])->sum('count');
            $item['recovery_weight_change_type2']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where('change_type',2)->where([['goods_category_id',$val['goods_category_id']]])->sum(DB::raw('weight*count'))+OrderRecoveryGoods::where($recovery_where)->where('change_type',2)->where([['goods_category_id',$val['goods_category_id']]])->sum(DB::raw('weight*count'));
            $item['recovery_cost_fee']=OrderSalesRecoveryGoods::where($sales_recovery_where)->where('change_type',2)->where([['goods_category_id',$val['goods_category_id']]])->sum(DB::raw('cost_fee*count'))+OrderRecoveryGoods::where($recovery_where)->where('change_type',2)->where([['goods_category_id',$val['goods_category_id']]])->sum(DB::raw('cost_fee*count'));



            $item['real_total_money']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('real_total_money');
//            $item['grossprofits']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('grossprofits')+OrderRecoveryGoods::where($sales_recovery_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('grossprofits');
            //毛利，用统计好的数据计算
            $item['grossprofits']=$item['real_total_money']+$item['recovery_valuations']-$item['cost_fee'];
            $item['label_price']=OrderSalesGoods::where($where)->where($sales_where)->where([['goods_category_id',$val['goods_category_id']]])->sum('label_price');
            $list_new[]=$item;
        }
        if($request->isdoexport==1){
            return $this->doexport($list_new);
        }


        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>['list'=>$list_new,'store_name'=>$store_name]]);

    }


    protected function doexport($list_new){
        $storeNames = array_unique(array_map(function($item) {
            return $item['store_name'];
        }, $list_new));
        $row=[
            ['goods_category_name'=>'销售毛利表'],
            ['goods_category_name'=>'所属门店：'.join(',' ,$storeNames)],
            [
            'goods_category_name'=>'商品类别',
            'count'=>'件数',
            'weight'=>'总件重',
            'netglod_weight'=>'总金重',
            'label_price'=>'标签价',
            'total_money'=>'销售金额',
            'cost_fee'=>'成本',
            'recovery_money'=>'换货金额',
            'recovery_count'=>'旧料件数',
            'recovery_weight'=>'旧料重量',
            'recovery_dold_fee'=>'折旧费',
            'recovery_valuations'=>'旧料估值',
            'recovery_count_change_type2'=>'上柜件数',
            'recovery_weight_change_type2'=>'上柜重量',
            'recovery_cost_fee'=>'上柜成本',
            'real_total_money'=>'实收金额',
            'grossprofits'=>'毛利',
        ]];
        $data=[];
        foreach($list_new as $val){
            $item=$val;
            $item['total_money']=intval($item['total_money'])/100;
            $item['cost_fee']=intval($item['cost_fee'])/100;
            $item['recovery_money']=intval($item['recovery_money'])/100;
            $item['recovery_dold_fee']=intval($item['recovery_dold_fee'])/100;
            $item['recovery_valuations']=intval($item['recovery_valuations'])/100;
            $item['recovery_cost_fee']=intval($item['recovery_cost_fee'])/100;
            $item['real_total_money']=intval($item['real_total_money'])/100;
            $item['grossprofits']=intval($item['grossprofits'])/100;
            $item['label_price']=intval($item['label_price'])/100;
            $data[]=$item;
        }

        $filename = '毛利表信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $data), $filename);
    }

}
